const Controller = require("egg").Controller;

class RoleController extends Controller {
  // 增
  async add() {
    const { ctx, service } = this;
    const roleService = service.role;
    const { rolename, desc } = ctx.request.body;
    // const creator = ctx.tokenUser.username;
    // console.log(creator);
    // 查看角色是否存在
    const name = await roleService.findByRoleName(rolename);
    if (name) {
      ctx.throw(409, "角色名已存在");
    }
    const role = await roleService.addRole(rolename, desc);
    ctx.apiSuc("新增成功", role);
  }
  // 删
  async del() {
    const { ctx, service } = this;
    const roleService = service.role;
    const id = +ctx.params.id;
    await roleService.delRoleInfo(id);
    ctx.apiSuc("删除成功", null);
  }
  // 改
  async edit() {
    const { ctx, service } = this;
    const roleService = service.role;
    const { rolename, desc, memberId } = ctx.request.body;
    const res = await roleService.editRoleInfo(rolename, desc, memberId);
    ctx.apiSuc("修改成功", res);
  }
  // 查
  async list() {
    const { ctx, service } = this;
    const roleService = service.role;
    let rolename = ctx.query.rolename;
    let creator = ctx.query.creator;
    const role = await roleService.findNameOrCreatorList(rolename, creator);
    ctx.apiSuc("获取成功", role);
  }
}

module.exports = RoleController;
